<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import * as echarts from "echarts";
import { defineProps } from "vue";
import geoJson from "./china.json";
import { useScreenStore } from "@/store/modules/screen";
const screenStore = useScreenStore();

// 从china.json中动态生成省份代码到省份名称的映射
const provinceCodeMap = {};
geoJson.features.forEach(feature => {
  provinceCodeMap[feature.id] = feature.properties.name;
});

// 1. 定义父组件传递的 props
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
});

const chartRef = ref(null);
let chartInstance = null;

// 数据转换函数：将store中的数据转换为地图所需格式
const convertStoreDataToMapData = (storeData, type) => {
  const result = [];
  storeData.forEach(item => {
    const provinceName = provinceCodeMap[item.key];
    if (provinceName) {
      result.push({
        name: provinceName,
        value: item.value,
        type: type // 'customer' 或 'dealer'
      });
    }
  });
  return result;
};

// 2. 封装初始化图表的函数（复用）
const initChart = async () => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);

  echarts.registerMap("china", geoJson);
  
  // 获取store中的数据
  const customerData = convertStoreDataToMapData(screenStore.customer_province_dic, 'customer');
  const dealerData = convertStoreDataToMapData(screenStore.dealer_province_dic, 'dealer');
  
  // 合并数据并创建地理坐标映射
  let geoCoordMap = {};
  let mapData = [];
  
  geoJson.features.forEach(function (item) {
    let name = item.properties.name,
      cp = item.properties.center;
    if (cp) {
      geoCoordMap[name] = cp; // 地区经纬度
      
      // 查找该省份的客户和经销商数据
      const customerItem = customerData.find(d => d.name === name);
      const dealerItem = dealerData.find(d => d.name === name);
      
      const customerCount = customerItem ? customerItem.value : 0;
      const dealerCount = dealerItem ? dealerItem.value : 0;
      
      // 只有有数据的省份才添加到地图上
      if (customerCount > 0 || dealerCount > 0) {
        mapData.push({
          name: name,
          value: cp.concat([customerCount + dealerCount, customerCount, dealerCount]),
          customerCount: customerCount,
          dealerCount: dealerCount
        });
      }
    }
  });

  let convertData = function (data) {
    let res = [];
    for (let i = 0; i < data.length; i++) {
      let geoCoord = geoCoordMap[data[i].name];
      if (geoCoord) {
        res.push({
          name: data[i].name,
          value: data[i].value, // 直接使用已经包含坐标的value
          customerCount: data[i].customerCount,
          dealerCount: data[i].dealerCount
        });
      }
    }
    return res;
  };
  
  // 计算最大值用于visualMap
  const maxValue = Math.max(...mapData.map(item => item.value[2]), 1);
  const option = {
    visualMap: {
      show: false,
      min: 0,
      max: maxValue,
      left: "left",
      top: "bottom",
      text: ["高", "低"],
      calculable: true,
      seriesIndex: [1],
      inRange: {
        color: ["#004693"]
      }
    },
    legend: {
      show: false
    },
    geo: {
      show: true,
      map: "china",
      roam: true,
      zoom: 1.25,
      label: {
        normal: {
          show: false,
        },
        emphasis: {
          show: false,
        },
      },
      itemStyle: {
        normal: {
          areaColor: "#031525",
          borderWidth: 1,
          borderColor: "#00CFFC",
        },
        emphasis: {
          areaColor: "#2B91B7",
        },
      },
    },
    series: [
      {
        name: "散点",
        type: "scatter",
        coordinateSystem: "geo",
        data: convertData(mapData),
        symbolSize: 5,
        label: {
          normal: {
            formatter: "{b}",
            position: "bottom",
            show: true,
          },
          emphasis: {
            show: true,
          },
        },
        itemStyle: {
          normal: {
            color: "red",
          },
        },
      },
      {
        type: "map",
        map: "china",
        geoIndex: 0,
        roam: true,
        aspectScale: 0.75,
        showLegendSymbol: false,
        label: {
          normal: {
            show: true,
          },
          emphasis: {
            show: false,
            textStyle: {
              color: "#fff",
            },
          },
        },
        itemStyle: {
          normal: {
            areaColor: "#031525",
            borderColor: "#3B5077",
          },
          emphasis: {
            areaColor: "#2B91B7",
          },
        },
        animation: false,
        data: mapData.map(item => ({
          name: item.name,
          value: item.value[2]
        })),
      },
      {
        name: "点",
        type: "scatter",
        coordinateSystem: "geo",
        symbol: "pin",
        symbolSize: function (val) {
          return 40;
        },
        label: {
          show: true,
          formatter: function (params) {
            return params.data.customerCount + params.data.dealerCount;
          },
          textStyle: {
            color: "#fff",
          },
        },
        itemStyle: {
          color: "#F62157",
        },
        zlevel: 6,
        data: convertData(mapData),
      },
    ]
  };
  chartInstance.setOption(option);
};

onMounted(() => {
  initChart(); // 组件挂载时初始化

  // 打印screen store中的数据
  console.log('客户省份分布数据 (customer_province_dic):', screenStore.customer_province_dic);
  console.log('经销商省份分布数据 (dealer_province_dic):', screenStore.dealer_province_dic);

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });
});

// 监听store中的数据变化
watch(
  () => [screenStore.customer_province_dic, screenStore.dealer_province_dic],
  () => {
    console.log('数据更新 - 客户省份分布:', screenStore.customer_province_dic);
    console.log('数据更新 - 经销商省份分布:', screenStore.dealer_province_dic);
    if (chartInstance) {
      initChart();
    }
  },
  { deep: true }
);

// 保留原有的props监听（如果需要）
watch(
  () => props.data,
  () => {
    if (chartInstance) {
      initChart();
    }
  }
);
</script>

<style scoped>
.chart-container {
  width: 100%;
  /* 自适应父容器宽度 */
  height: 100%;
}
</style>
